package com.nf;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MiniDbutils {
    public static void close(Connection conn) throws SQLException {
        if (conn!=null) {
            conn.close();
        }
    }

    public static void close(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }

    public static void close(Statement stmt) throws SQLException {
        if (stmt != null) {
            stmt.close();
        }
    }

    public static void closeComplete(Connection conn, ResultSet rs, Statement stmt) throws SQLException {
        if (conn != null) {
            conn.close();
        }else if (rs != null) {
            rs.close();
        } else if (stmt != null) {
            stmt.close();
        }
        close(rs);
        close(stmt);
        close(conn);

        if(conn!=null && rs!=null && stmt!=null){
            conn.close();
            rs.close();
            stmt.close();
        }
    }

    public static void closeQuietly(Connection conn) {
        try {
            //方法的其中一个作用，减少代码重复，可以重复利用不为null的判断逻辑
            close(conn);
        } catch (SQLException throwables) {
            //如果出了错，直接捕获不做任何处理，
            //这会导致调用此方法的地方不知道发生了什么错误
        }
    }

    public static void closeQuietly(ResultSet resultSet) {
        try {
            close(resultSet);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void closeQuietly(Statement stmt) {
        try {
            close(stmt);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void closeQuietly(Connection con, ResultSet rs, Statement stmt) {
        try {
            closeQuietly(rs);
        } finally {
            try {
                closeQuietly(stmt);
            } finally {
                closeQuietly(con);
            }
        }
    }

}
